
import { defineStore } from 'pinia';
import { ref } from 'vue';
//如果需要计算属性 引入计算属性
import { computed } from 'vue';
// 涉及异步调用  这里引入了axios 正常是引入请求
import axios from 'axios'

interface Carts {
    id: string
    name: string
    price: number
    count: number
    thumb: string
}

export const CartStore = defineStore('cart', () => {
    const list = ref<Carts[]>([])
    const goods = ref()
    const updateList = (newList: Carts[]) => {
        list.value = newList
    }
    const updateCount = (obj: { id: string; count: number; }) => {
        goods.value = list.value.find(item => item.id === obj.id)
        goods.value.count = obj.count
    }
    const getList = async () => {
        const res = await axios.get('http://localhost:3000/cart')
        updateList(res.data)
    }

    const updateCountAsync = async (obj: { id: string; newCount: number; }) => {
        await axios.patch(`http://localhost:3000/cart/${obj.id}`, {
            count: obj.newCount
        })
        updateCount(
            {
                id: obj.id,
                count: obj.newCount
            }
        )
    }

    return { list, updateList, getList, updateCountAsync }
})